<template>
  <div style="height: 100%; background-color: #fff">
    <div class="head_center" style="background-color: rgba(0, 0, 0, 0.05)">
      <img class="login-logo" src="@/assets/img/login/logo-orange.png" />
    </div>
    <div clsaa="top-content" style="margin-top: 200px">
      <div class="title">
        {{ LANG.UNIFIED_LOGIN }}
      </div>
      <div class="main-content" style="display: flex">
        <div class="main-left">
          <div v-show="isPwdLogin">
            <div style="margin-top: 50px">
              <fks-input
                v-model="loginForm.userName"
                class="login-input1"
                :placeholder="LANG.ACCOUNT_NAME"
              />
            </div>
            <div>
              <fks-input
                v-model="loginForm.password"
                type="password"
                maxlength="50"
                class="login-input2"
                :placeholder="LANG.ACCOUNT_PWD"
                @keyup.native.enter="handleLogin"
              />
            </div>
            <div v-show="imgCaptchaValidate">
              <fks-input
                v-model="loginForm.img_code"
                class="login-input2"
                style="width: 70%; margin-top: 12px; vertical-align: middle"
                :placeholder="LANG.ACCOUNT_CAPTCAH"
                maxlength="50"
                @keyup.native.enter="handleLogin"
              />
              <div class="validate-img-wapper">
                <img class="validate-img" :src="captchaImg" @click="getImg" />
              </div>
            </div>
            <span class="changeLogin" @click="changeSmsLogin">{{
              LANG.SMS_LOGIN
            }}</span>
            <fks-button
              type="primary"
              style="width: 360px; margin-top: 24px; font-size: 18px"
              :class="{ active: active, isActive: isActive, primary: primary }"
              :disabled="disabled"
              :loading="loading"
              @click="handleLogin"
            >
              {{ LANG.AUTH_LOGIN }}
            </fks-button>
          </div>

          <div v-show="!isPwdLogin">
            <div style="margin-top: 50px">
              <fks-input
                v-model="loginForm.phone"
                class="login-input1"
                maxlength="50"
                :placeholder="LANG.PHONE_TIP"
                oninput="value=value.replace(/[^\d]/g,'')"
              />
            </div>
            <div>
              <fks-input
                v-model="loginForm.captcha_code"
                class="login-input2"
                maxlength="50"
                oninput="value=value.replace(/[^\d]/g,'')"
                :placeholder="LANG.PHONE_CAPTCAH"
                @keyup.native.enter="handleLogin"
              >
                <fks-button
                  slot="suffix"
                  type="text"
                  :disabled="smsDisabled"
                  :class="{ smsDisabled: smsDisabled }"
                  @click="getSms"
                >
                  <span
                    v-if="countDown != -1 && countDown != -2"
                    class="word"
                    >{{ countDown + 's' }}</span
                  >
                  <span
                    v-if="countDown != -1 || countDown != -2"
                    style="line-height: 28px"
                    :class="{ disabled: smsDisabled }"
                    >{{
                      countDown == -2 ? LANG.GET_CAPTCHA : LANG.REGAIN_CAPTCHA
                    }}</span
                  >
                </fks-button>
              </fks-input>
            </div>
            <span class="changeLogin" @click="changeLogin">{{
              LANG.ACCOUNT_LOGIN
            }}</span>
            <fks-button
              type="primary"
              style="width: 360px; margin-top: 24px; font-size: 18px"
              :class="{ active: active, isActive: isActive, primary: primary }"
              :disabled="disabled"
              :loading="loading"
              @click="handleLogin"
            >
              {{ LANG.AUTH_LOGIN }}
            </fks-button>
          </div>
        </div>
        <div class="divider-line" />
        <div class="main-right">
          <div class="auth-list">
            <div class="auth-tip">
              {{ LANG.AUTH_TIP }}
            </div>
            <p style="width: 800px">
              <span style="margin-top: 24px; color: #757575">{{
                LANG.LINK_ACCOUNT
              }}</span>
            </p>
            <p style="width: 800px">
              <span style="color: #757575">{{ LANG.GET_INFO_TIP }}</span>
            </p>
            <p class="privacy-state" style="width: 800px; color: #757575">
              {{ LANG.SHARING_TIP }}
            </p>
          </div>
        </div>
      </div>
      <div class="footer" />
    </div>
  </div>
</template>
<script>
import * as login from './api'
import { GRANT_TYPE, prefix } from '@/config'
import { pwdEncrypt } from '@/utils/encryption/pwd'
import Mix from '@/mixins/module'
export default {
  name: 'UnifiedLogin',
  components: {},
  mixins: [Mix],
  data() {
    return {
      loginForm: {
        userName: '',
        password: '',
        phone: '',
        captcha_code: '',
        img_code: ''
      },
      countDown: -2,
      urlParams: {},
      active: false,
      isActive: true,
      primary: true,
      disabled: false,
      isPwdLogin: true,
      loading: false,
      errorCount: 3,
      errorParams: {},
      captcha_key: '',
      img_key: '',
      captchaImg: '',
      smsDisabled: true,
      imgCaptchaValidate: false
    }
  },
  watch: {
    loginForm: {
      deep: true,
      immediate: true,
      handler(val) {
        if (
          (val.userName && val.password && this.isPwdLogin) ||
          (val.phone && val.captcha_code && !this.isPwdLogin)
        ) {
          this.disabled = false
          this.active = true
          this.isActive = false
        } else if (val.phone && this.countDown == -2) {
          this.smsDisabled = false
          this.disabled = true
          this.isActive = true
        } else {
          this.disabled = true
          this.isActive = true
          this.smsDisabled = true
        }
      }
    },
    'loginForm.userName'(val) {
      if (this.errorParams) {
        if (this.loginForm.userName) {
          if (!this.errorParams.hasOwnProperty(this.loginForm.userName)) {
            this.imgCaptchaValidate = false
          } else {
            if (this.errorParams[this.loginForm.userName] > this.errorCount) {
              this.imgCaptchaValidate = true
              this.getImg()
            } else {
              this.imgCaptchaValidate = false
            }
          }
        } else {
          this.imgCaptchaValidate = false
        }
      }
    }
  },
  created() {
    this.urlParams = this.$route.query
    this.errorParams = JSON.parse(localStorage.getItem(prefix + 'errorParams'))
    if (this.errorParams) {
      if (this.loginForm.username) {
        if (this.errorParams.hasOwnProperty(this.loginForm.username)) {
          if (this.errorParams[this.loginForm.userName] > this.errorCount)
            this.imgCaptchaValidate = true
          this.getImg()
        }
      } else {
        this.imgCaptchaValidate = false
      }
    } else {
      this.errorParams = {}
    }
  },
  methods: {
    changeSmsLogin() {
      this.isPwdLogin = false
      this.loginForm.phone = ''
      this.loginForm.captcha_code = ''
      this.disabled = true
      this.isActive = true
    },
    changeLogin() {
      this.isPwdLogin = true
      this.disabled = true
      this.isActive = true
      this.loginForm.userName = ''
      this.loginForm.password = ''
    },
    getSms() {
      login
        .getSMSCaptcha({ phone: this.loginForm.phone })
        .then((res) => {
          if (res.status) {
            this.captcha_key = res.data.data
            this.updataCountDown()
          } else {
            this.smsDisabled = true
            this.updataCountDown()
          }
        })
        .catch((err) => {
          this.smsDisabled = true
          this.updataCountDown()
        })
    },
    updataErrorParam() {
      let un = this.loginForm.userName
      if (this.errorParams) {
        if (this.errorParams.hasOwnProperty(un)) {
          this.errorParams[un]++
        } else {
          this.errorParams[un] = 1
        }
        if (this.errorParams[un] + 1 > this.errorCount) {
          this.imgCaptchaValidate = true
        }
      } else {
        this.errorParams[un] = 1
      }
      localStorage.setItem(
        prefix + 'errorParams',
        JSON.stringify(this.errorParams)
      )
      if (this.imgCaptchaValidate) {
        this.getImg()
      }
    },
    updataCountDown() {
      this.countDown = 60
      const count = setInterval(() => {
        if (this.countDown == 0) {
          clearInterval(count)
          this.countDown = -1
          this.smsDisabled = false
        } else {
          this.countDown--
        }
      }, 1000)
    },
    getImg() {
      login
        .getImgCaptcha()
        .then((res) => {
          if (res) {
            this.img_key = res.key
            this.captchaImg = res.img
          }
        })
        .catch((error) => {
          console.log(error)
        })
    },
    handleLogin() {
      let loginData = this.getLoginData()

      this.loading = true
      login
        .getToken(loginData)
        .then(async (res) => {
          if (res.access_token) {
            await this.$store.dispatch('loadingUserData', res)
            this.loading = false
            this.imgCaptchaValidate = false
            this.errorParams[this.loginForm.userName] = 0
            localStorage.setItem(
              prefix + 'errorParams',
              JSON.stringify(this.errorParams)
            )
            this.updataErrorParam()
            this.redirectTo('/demo/SSO')
          }
        })
        .catch((error) => {
          this.$message.error(error.response.data)
          this.loading = false
          this.updataErrorParam()
        })
    },
    getLoginData() {
      let form = {}
      if (this.isPwdLogin) {
        form.grant_type = GRANT_TYPE.password.code
        form.username = this.loginForm.userName
        // if (this.urlParams) {
        //   form.client_id = this.urlParams.client_id
        //   form.redirect_url = this.urlParams.redirect_url
        //   form.response_type = this.urlParams.response_type
        // }
        if (this.loginForm.password) {
          form.password = pwdEncrypt(this.loginForm.password)
        } else {
          form.password = this.loginForm.password
        }
        if (this.imgCaptchaValidate) {
          form.grant_type = GRANT_TYPE.img_captcha.code
          form.captcha_key = this.img_key
          form.captcha_code = this.loginForm.img_code
        }
        return form
      } else {
        let form = {}
        form.grant_type = GRANT_TYPE.sms_captcha.code
        form.username = this.loginForm.phone
        form.captcha_code = this.loginForm.captcha_code
        form.captcha_key = this.captcha_key
        return form
      }
    }
  }
}
</script>
<style  lang="scss" scoped>
.title {
  width: 100%;
  font-weight: 200;
  font-size: 32px;
  text-align: center;
}

.main-left {
  position: relative;
  display: inline-block;
  width: 360px;
  margin-left: auto;
  vertical-align: top;
}

.login-input1 {
  margin-bottom: 24px;
}

::v-deep .fks-input__inner {
  height: 48px !important;
  border: none;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.05);
}

.login-input2 {
  margin-bottom: 12px;
}

.changeLogin {
  font-size: 14px;
  text-align: left;
  color: #007dff;
  cursor: pointer;
}

.divider-line {
  display: inline-block;
  width: 1px;
  height: 320px;
  margin: 50px 60px 0;
  vertical-align: top;
  background: rgba(0, 0, 0, 0.1);
}

.main-right {
  z-index: 0;
  display: inline-block;
  width: 360px;
  margin-right: auto;
  vertical-align: top;
}

.auth-tip {
  width: 900px;
  margin-top: 24px;
  margin-top: 50px;
  font-size: 16px;
  line-height: 22px;
  text-align: left;
}

.isActive {
  opacity: 0.38;
  cursor: default !important;
}

.primary {
  border: none;
  border-radius: 6.4px;
  background: #007dff;
}

.disabled {
  margin-top: 12px !important;
  color: #007dff;
  opacity: 0.38;
  cursor: default !important;
}

.fks-button--primary {
  height: 48px;
  background-color: #007dff !important;
}

.smsDisabled {
  cursor: default !important;
}

.validate-img-wapper {
  position: relative;
  display: inline-block;
  width: 20%;
  height: 44px;
  border-radius: 4px;
  text-align: center;
  vertical-align: middle;
}

.validate-img {
  height: 100%;
}

.login-logo {
  position: absolute;
  top: 20px;
  left: 30px;
  width: 100px;
}
</style>
